using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.suppliercontacts;
using SupplierCustomerManagement.Read.API.Dtos;

namespace SupplierCustomerManagement.Read.API.Controllers
{
    /// <summary>
    /// 供应商联系人查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class SupplierContactsController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IMapper _mapper;
        private readonly ILogger<SupplierContactsController> _logger;

        public SupplierContactsController(
            IMediator mediator,
            IMapper mapper,
            ILogger<SupplierContactsController> logger)
        {
            _mediator = mediator;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 获取供应商联系人列表
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>分页查询结果</returns>
        [HttpGet]
        public async Task<ApiPaging<SupplierContactListDto>> GetSupplierContacts([FromQuery] GetSupplierContactsQuery query)
        {
            try
            {
                _logger.LogInformation("开始查询供应商联系人列表，页码: {PageIndex}, 每页大小: {PageSize}", 
                    query.PageIndex, query.PageSize);

                // 发送查询命令
                var result = await _mediator.Send(query);

                if (result.code == ResultEnumCode.Ok)
                {
                    _logger.LogInformation("成功查询供应商联系人列表，总数量: {TotalCount}, 当前页数量: {CurrentPageCount}", 
                        result.TotalCount, result.PageData?.Count ?? 0);
                }
                else
                {
                    _logger.LogWarning("查询供应商联系人列表失败: {Message}", result.message);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询供应商联系人列表时发生异常");
                
                return new ApiPaging<SupplierContactListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询供应商联系人列表时发生异常: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<SupplierContactListDto>()
                };
            }
        }
    }
} 